import '@umijs/max';
import React, { useEffect, useState } from 'react';
import { Card, Space, message, Row, Col } from 'antd';

import {
  getMyBiProductsServiceUsagesUsingGet,
  listBiProductsVoByPageUsingPost,
  placeAnOrderUsingPost,
} from '@/services/api/biProductsController';
import { Statistic } from '@ant-design/pro-components';
import { FundProjectionScreenOutlined } from '@ant-design/icons';

/**
 * 我的服务使用页面
 *
 * @constructor
 */
const MyServiceUsagePage: React.FC = () => {
  const [biProductsList, setBiProductsList] = useState<API.BiProductsVO[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [productsServiceUsages, setProductsServiceUsages] = useState<API.ServiceUsage>({});

  const loadMyServiceUsage = async () => {
    try {
      const res = await getMyBiProductsServiceUsagesUsingGet();
      if (res.data) {
        setProductsServiceUsages(res.data);
      } else {
        setProductsServiceUsages({
          leftTokens: 0,
          tokensConsumed: 0,
          useCount: 0,
        });
      }
    } catch (e) {}
  };

  const loadData = async () => {
    try {
      setLoading(true);
      const res = await listBiProductsVoByPageUsingPost({});
      if (res.data) {
        setBiProductsList(res.data.records ?? []);
      } else {
        setBiProductsList([]);
        message.error('获取BI产品失败');
      }
    } catch (e: any) {
      message.error('获取BI产品失败 ' + e.message);
    }
    setLoading(false);
  };

  const placeAnOrderHandle = async (id: any) => {
    if (!id) return;
    const res = await placeAnOrderUsingPost({ productsId: id });

    if (res) {
      // 创建一个新的<form>元素
      const div = document.createElement('divform');
      div.innerHTML = res;
      document.body.appendChild(div);
      document.forms[0].acceptCharset = 'UTF-8'; //保持与支付宝默认编码格式一致，如果不一致将会出现：调试错误，请回到请求来源地，重新发起请求，错误代码 invalid-signature 错误原因: 验签出错，建议检查签名字符串或签名私钥与应用公钥是否匹配
      document.forms[0].submit();
    }
  };

  /**
   * 搜索参数
   */
  useEffect(() => {
    loadMyServiceUsage();
    loadData();
  }, []);

  return (
    <div className="my-service-usage-page">
      <Card title={'我的余额'}>
        <Row gutter={[10, 16]}>
          <Col span={6}>
            <Card bordered={false} hoverable={true}>
              <Statistic
                title="剩余Tokens"
                value={productsServiceUsages.leftTokens}
                valueStyle={{ color: 'red' }}
                prefix={<FundProjectionScreenOutlined />}
                suffix={'tokens'}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card bordered={false} hoverable={true}>
              <Statistic
                title="总调用次数"
                value={productsServiceUsages.useCount}
                valueStyle={{ color: 'red' }}
                prefix={<FundProjectionScreenOutlined />}
                suffix={'次'}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card bordered={false} hoverable={true}>
              <Statistic
                title="总消耗Tokens"
                value={productsServiceUsages.tokensConsumed}
                valueStyle={{ color: 'red' }}
                prefix={<FundProjectionScreenOutlined />}
                suffix={'tokens'}
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card bordered={false} hoverable={true}>
              <Statistic
                title="单次调用平均消耗Tokens"
                value={
                  productsServiceUsages.tokensConsumed && productsServiceUsages.useCount
                    ? (
                        productsServiceUsages.tokensConsumed / productsServiceUsages.useCount
                      ).toFixed(3)
                    : 0
                }
                valueStyle={{ color: 'red' }}
                prefix={<FundProjectionScreenOutlined />}
                suffix={'tokens/次'}
              />
            </Card>
          </Col>
        </Row>
      </Card>
      <Card title={'产品列表'} loading={loading}>
        <Space direction="horizontal" size={16} wrap>
          {biProductsList.map((product) => (
            <Card
              bordered={false}
              hoverable={true}
              key={product.id}
              style={{
                borderColor: "red",
                borderRadius: 8,
                backgroundColor: 'rgb(255,250,250)',
                textAlign: 'center',
              }}
              onClick={() => placeAnOrderHandle(product.id)}
            >
              <h3>{product.name}</h3>
              <h3>{product.price + '￥'}</h3>
              <h3 style={{ color: 'red' }}>充值</h3>
            </Card>
          ))}
        </Space>
      </Card>
    </div>
  );
};
export default MyServiceUsagePage;
